import { useState, useEffect } from 'react';

/**
 * 表单数据收集组件
 * @param {Object} props
 * @param {Element|string} props.container - 包含表单的容器元素或选择器
 * @param {string} props.formItemSelector - 表单项选择器，默认为'.el-form-item'
 * @param {string} props.labelSelector - 标签选择器，默认为直接子元素
 * @param {string} props.inputSelector - 输入框选择器，默认为'input'
 * @param {Function} props.onDataCollected - 数据收集完成后的回调函数
 * @param {number} props.delay - 收集数据的延迟时间（毫秒）
 * @returns {Object} 收集到的表单数据
 */
const FormDataCollector = ({
  container,
  formItemSelector = '.el-form-item',
  labelSelector = 'children[0]',
  inputSelector = 'input',
  onDataCollected,
  delay = 1000
}) => {
  const [formData, setFormData] = useState({});

  useEffect(() => {
    // 获取容器元素
    const containerElement = typeof container === 'string'
      ? document.querySelector(container)
      : container;

    if (!containerElement) {
      console.warn('FormDataCollector: 容器元素未找到');
      return;
    }

    // 收集表单数据
    const collectFormData = () => {
      const formItemList = containerElement.querySelectorAll(formItemSelector);
      const tempFormData = {};

      formItemList.forEach(item => {
        // 获取标签文本
        const labelElement = labelSelector === 'children[0]' 
          ? item.children[0] 
          : item.querySelector(labelSelector);
        
        if (!labelElement) return;
        
        const labelText = labelElement.textContent;
        
        // 获取输入框
        const inputElement = item.querySelector(inputSelector);
        
        if (inputElement) {
          tempFormData[labelText] = {
            value: inputElement.value,
            dom: inputElement
          };
        }
      });

      setFormData(tempFormData);
      
      if (onDataCollected && Object.keys(tempFormData).length > 0) {
        onDataCollected(tempFormData);
      }
    };

    // 延迟收集数据
    const timerId = setTimeout(collectFormData, delay);

    // 清理函数
    return () => clearTimeout(timerId);
  }, [container, formItemSelector, labelSelector, inputSelector, onDataCollected, delay]);

  return formData;
};

export default FormDataCollector;